package cn.xxm.ff.log.common.utils;

import cn.xxm.ff.log.core.dto.CustomDesensitizeType;
import cn.xxm.ff.log.core.enums.DesensitizationTypeEnum;
import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.xxm.ff.log.core.enums.DesensitizationTypeEnum.CustKeyNamesChinese;
import static cn.xxm.ff.log.core.enums.DesensitizationTypeEnum.CustKeyNamesEnglish;


/**
 * Created by xuxiaoming005 on 2018-08-22.
 */
public class DesensitizationHelper {

    /**
     * 预处理json字符串信息
     * @param formattedMessage 格式化的消息
     * @param beginIndex json字符串开始位置
     * @param endIndex json字符串结束位置
     * @return 处理过循环引用的json字符串
     */
    public static String preHandleJsonString(String formattedMessage, int beginIndex, int endIndex) {
        String substring = formattedMessage.substring(beginIndex, endIndex + 1);
        if (StringUtils.contains(substring, "\\\"")) {
            substring = StringUtils.replace(substring, "\\\"", "\"");
        }

        substring = handleStringBeforeParse(substring);
        return substring;
    }

    public static String getXinXin(int length) {
        StringBuffer strB = new StringBuffer();
        for (int i = 0; i < length; i++) {
            strB.append("*");
        }
        return strB.toString();
    }

    public static boolean isChinese(String str) {
        String regexStr = "[\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regexStr);
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static String handleStringBeforeParse(String input) {
        if (StringUtils.isBlank(input)) {
            return "";
        }

        String pattern1 = "\\{\"\\$ref\":\"[@\\$]\"\\}";
        String pattern2 = "\\{\"\\$ref\":\"(\\.){2}\"\\}";
        String pattern3 = "\\{\"\\$ref\":\"(\\$\\.children\\.\\d+)\"\\}";
        return input.replaceAll(pattern1, "null")
                .replaceAll(pattern2, "null")
                .replaceAll(pattern3, "null");
    }



    public static String processArrayValue(String replacement, CustomDesensitizeType type) {
        if (StringUtils.isBlank(replacement)) {
            return "";
        }

        String[] valueItems = replacement.split(",");
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.contains(replacement, "\"")) {
            for (String valueItem: valueItems) {
                stringBuilder.append(processStringValue(valueItem, type)).append(",");
            }
        } else {
            for (String valueItem: valueItems) {
                stringBuilder.append(processNumberValue(valueItem, type)).append(",");
            }
        }

        if (stringBuilder.length() == 0){
            return "";
        }

        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    public static String processNumberValue(String val, CustomDesensitizeType type) {
        if (StringUtils.isBlank(val)) {
            return "";
        }

        if (StringUtils.equalsIgnoreCase(type.getType(),
                DesensitizationTypeEnum.EmailKeyNames.getType())) {
            String[] vals = val.trim().split("@");
            if (StringUtils.isNotBlank(vals[0])
                    && vals.length == 2) {
                return maskValue(vals[0], type) + "@" + vals[1];
            }

            return "";
        } else if (StringUtils.equalsIgnoreCase(type.getType(),
                CustKeyNamesChinese.getType())) {
            // 处理中文
            if (isChinese(val)) {
                type.setStartIndex(CustKeyNamesChinese.getStartIndex());
                type.setEndIndex(CustKeyNamesChinese.getEndIndex());
            } else {
                type.setStartIndex(CustKeyNamesEnglish.getStartIndex());
                type.setEndIndex(CustKeyNamesEnglish.getEndIndex());
            }
            return maskValue(val.trim(), type);
        }

        return maskValue(val.trim(), type);
    }

    public static String processStringValue(String val, CustomDesensitizeType type) {
        if (StringUtils.isBlank(val)) {
            return "";
        }

        String valItem = val.trim();
        valItem = valItem.substring(1, valItem.lastIndexOf("\""));

        return "\"" + processNumberValue(valItem, type) + "\"";
    }

    public static String maskValue(String valItem, CustomDesensitizeType type) {
        if (valItem.length() < type.getStartIndex()) {
            return valItem;
        }

        int xinxinLength = valItem.length() - type.getStartIndex() - type.getEndIndex();
        if (xinxinLength <= 0) {
            return StringUtils.substring(valItem, 0, type.getStartIndex())
                    + getXinXin(1);
        }

        return StringUtils.substring(valItem, 0, type.getStartIndex())
                + getXinXin(xinxinLength)
                + StringUtils.substring(valItem, valItem.length() - type.getEndIndex());
    }

}
